import VuiElement from '../../base/element';
import VuiArrowDown from '../../components/arrow/arrow-down';
import VuiContainer from '../../components/container';
import VuiDropdown from '../../components/dropdown';
import VuiText from '../../components/text';
import './style.css';

export default class VuiComboBox extends VuiElement {
  constructor(config) {
    super();
    const defaultConfig = {
      id: null,
      enabled: true,
      textWidth: 80,
      dropdownWidth: 120,
      defaultValue: '请选择...',
      options: [],
      title: null,
      showTitle: false,
      action: _ => {}
    };

    this._config = Object.assign(defaultConfig, config);
    this._className = {
      container: 'vui-combobox',
      content: 'vui-combobox-content',
      title: 'vui-combobox-title',
      text: 'vui-combobox-text',
      arrow: 'vui-combobox-arrow'
    };
  }

  initUI() {
    const cls = this._className;
    const config = this._config;
    // 容器
    this.initContainer(null, null, config.id);

    // 标题
    if (config.showTitle) {
      const title = VuiText.newInstance(config.title, cls.title);
      this.append(title);
    }

    const content = VuiContainer.newInstance(cls.content);
    // 文字
    const text = VuiText.newInstance(config.defaultValue, cls.text);
    text.setWidth(config.textWidth);
    content.append(text);

    // 下拉箭头
    const arrow = VuiArrowDown.newInstance();
    arrow.addClass(cls.arrow);
    content.append(arrow);

    // 下拉列表
    const dp = VuiDropdown.newInstance();
    dp.setWidth(config.dropdownWidth);
    dp.setTopLeft(26, 0);

    dp.setOptions(config.options, (value, text) => {
      this.safeRun(config.action, value);
      this.setText(text);
    });
    const dpToggle = evt => {
      if (config.enabled) {
        dp.toggle();
      }
      evt.stopPropagation();
    };

    // text.addEventListener('click', dpToggle);
    // arrow.addEventListener('click', dpToggle);
    content.addEventListener('click', dpToggle);

    this.text = text;
    this.dropdown = dp;
    this.append(content);
    this.append(dp);
  }

  setText(text) {
    this.text.setInnerText(text);
  }

  setClickListener(listener) {
    if (typeof listener === 'function') {
      this._config.action = listener;
    }
  }
}
